
package org.hang.gift;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;

import java.io.IOException;

/**
 * Examples of uploading with enabling checkpoint file.
 *
 */
public class UploadSample {

    // oss地址
    private static String endpoint = "https://oss-cn-chengdu.aliyuncs.com";

    // 子账号的id
    private static String accessKeyId = "LTAI5tRVEcpoardqGFM6Jgck";
    private static String accessKeySecret = "VVncZWWC8pc1SsaixRiHWIP3WlMejI";
    // 桶名
    private static String bucketName = "gift-hang";
    // 上传到oss以后的文件名
    private static String key = "lan3.jpg";
    // 要上传文件的本地地址
    private static String uploadFile = "C:\\Users\\Lenovo\\Desktop\\youjian\\lan3.jpg";

    public static void main(String[] args) throws IOException {        

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        
        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key);

            uploadFileRequest.setUploadFile(uploadFile);

            uploadFileRequest.setTaskNum(5);

            uploadFileRequest.setPartSize(1024 * 1024 * 1);

            uploadFileRequest.setEnableCheckpoint(true);
            
            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
            
            CompleteMultipartUploadResult multipartUploadResult = 
                    uploadResult.getMultipartUploadResult();
            System.out.println(multipartUploadResult.getETag());
            
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }
}
